package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;


@Service
public class WeChatServiceImpl implements WeChatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //封装请求参数
        HashMap<String, Object> params = new HashMap<>();
        params.put("js_code", code);
        params.put("appid", appid);
        params.put("secret", secret);

        String result = HttpUtil.get(REQUEST_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Object errcode = jsonObject.get("errcode");
        if (ObjectUtil.isNotNull(errcode)) {
            throw new BaseException("认证失败");
        }
        String openid = jsonObject.getString("openid");
        return openid;

    }

    /**
     * 获取手机号码
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhoneNumber(String phoneCode) {
        //封装请求参数
        HashMap<String, Object> params = new HashMap<>();
        params.put("code", phoneCode);
        String accessToken = getAccessToken();
        //请求微信后端
        String result = HttpUtil.post(PHONE_REQUEST_URL + accessToken, JSONUtil.toJsonStr(params));
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer errcode = jsonObject.getInteger("errcode");
        if (!errcode.equals(0)) {
            throw new BaseException("获取电话号码失效");
        }
        String phoneNumber = jsonObject.getJSONObject("phone_info").getString("phoneNumber");
        return phoneNumber;

    }

    private String getAccessToken() {
        //获取access_token
        //封装请求参数
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        String result = HttpUtil.get(TOKEN_URL, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }
}
